package com.itqf.filter;

import com.netflix.zuul.ZuulFilter;
import com.netflix.zuul.context.RequestContext;
import com.netflix.zuul.exception.ZuulException;
import org.springframework.cloud.netflix.zuul.filters.support.FilterConstants;
import org.springframework.http.HttpStatus;
import org.springframework.stereotype.Component;

import javax.servlet.http.HttpServletRequest;

/**
 * @Description:
 * @Company: 千锋互联
 * @Author: 李丽婷
 * @Date: 2021/3/18
 * @Time: 下午5:39
 */
@Component
public class TokenFilter extends ZuulFilter {
    @Override
    public String filterType() {
        return FilterConstants.PRE_TYPE;//
        // "error";
        //    public static final String POST_TYPE = "post"; 目标服务访问后执行
        //    public static final String PRE_TYPE = "pre";前
        //    public static final String ROUTE_TYPE = "route";//路由  动态路由
    }

    @Override
    public int filterOrder() {
        return 0;//越小 优先级越高
    }

    @Override
    public boolean shouldFilter() {

        return RequestContext.getCurrentContext().sendZuulResponse();//false
    }

    @Override
    public Object run() throws ZuulException {
        //1,请求上下文
        RequestContext context = RequestContext.getCurrentContext();
        //2.请求对象
        HttpServletRequest request =  context.getRequest();
        //?token=
        String  token = request.getParameter("token");
        if (token!=null&&token.equals("djisndskdnks")){
            System.out.println("token正确......");
        }else{
            //错误的token   或者   没有传token
            context.setSendZuulResponse(false);//不路由  不调用目标服务
            context.setResponseStatusCode(HttpStatus.UNAUTHORIZED.value());
        }


        return null;
    }
}
